import Vue from 'vue'
import Loading from './Loading'

const LoadingComponent = Vue.extend(Loading)

const toggleLoading = (el, binding) => {
  if (binding.value) {
    Vue.nextTick(() => {
      // 控制loading组件显示
      el.instance.visible = true
      // 插入到目标元素
      insertElement(el, el, binding)
    })
  } else {
    el.instance.visible = false
  }
}

const insertElement = (parent, el) => {
  // 给父元素加个定位，让loading元素定位
  el.style.position = 'relative';
  parent.appendChild(el.loadingComponent)
}

export default {
  /**
   * 只调用一次，指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。
   * @param {*} el 
   * @param {*} binding 
   * @param {*} vnode 
   */
  bind: function (el, binding, vnode) {
    const loadingComponent = new LoadingComponent({
      el: document.createElement('div'),
      data () { }
    })
    el.instance = loadingComponent
    el.loadingComponent = loadingComponent.$el
    el.loadingComponentStyle = {}
    binding.value && toggleLoading(el, binding)
  },
  update: function (el, binding) {
    if (binding.oldValue !== binding.value) {
      toggleLoading(el, binding)
    }
  },
  /**
   * 只调用一次，指令与元素解绑时调用。
   * @param {*} el 
   * @param {*} binding 
   */
  unbind: function (el, binding) {
    el.style.position = '';
    el.instance && el.instance.$destroy()
  }
}